package com.zrrd.sort;

import sun.applet.Main;

import java.lang.reflect.Array;
import java.util.Arrays;

public class MergeSort {
    public void mergeSort(int[] array) {
        if (array.length <= 1) {
            return;
        }
        int middle = (0 + array.length - 1) / 2;
        int[] left = Arrays.copyOfRange(array, 0, middle + 1);
        int[] right = Arrays.copyOfRange(array, middle + 1, array.length);
        mergeSort(left);
        mergeSort(right);
        int i = 0, j = 0, k = 0;
        while (i < left.length && j < right.length) {
            if (left[i] <= right[j]) {
                array[k++] = left[i++];
            } else {
                array[k++] = right[j++];
            }
        }
        if (i < left.length) {
            while (i < left.length) {
                array[k++] = left[i++];
            }
        }
        if (j < right.length) {
            while (j < right.length) {
                array[k++] = right[j++];
            }
        }
    }

    public void mergeSortInner(int[] array, int[] temp, int start, int end) {
        if (start >= end) {
            return;
        }
        int middle = (start + end) / 2;
        mergeSortInner(array, temp, start, middle);
        mergeSortInner(array, temp, middle + 1, end);
        int i = start;
        int j = middle + 1;
        int k = start;
        while (i <= middle && j <= end) {
            if (array[i] <= array[j]) {
                temp[k++] = array[i++];
            } else {
                temp[k++] = array[j++];
            }
        }
        if (i <= middle) {
            while (i <= middle) {
                temp[k++] = array[i++];
            }
        }
        if (j <= end) {
            while (j <= end) {
                temp[k++] = array[j++];
            }
        }
        for (int l = start; l <= end; l++) {
            array[l] = temp[l];
        }
    }

    public void mergeSortOptimized(int[] arr) {
        int[] temp = new int[arr.length];
        mergeSortInner(arr, temp, 0, arr.length - 1);
    }

    public static void main(String[] args) {
        MergeSort ms = new MergeSort();
        int[] array = new int[]{4, 2, 1, 0, 6, 7, 9, 8, 5};
        ms.mergeSortOptimized(array);
        System.out.println(Arrays.toString(array));
    }
}
